package com.x.erp.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.x.erp.model.Apk;
import com.x.framework.dao.BaseDao;

/**
 * app安装包版本信息DAO
 */
@Repository
public class ApkDao extends BaseDao {

	private final static String selectApkListSql = "SELECT ba.* FROM BASE_APK ba WHERE 1=1 ";
	/**
	 * 查询app安装包版本列表
	 * @param apk
	 * @return
	 * @throws Exception
	 */
	public List<Apk> selectApkList(Apk apk) throws Exception{
		StringBuilder sql = new StringBuilder(selectApkListSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, apk);
		sql.append("ORDER BY ba.APK_VERSION DESC ");
		return this.queryForList(sql.toString(), Apk.class, params, apk);
	}

	private final static String selectApkNumSql = "SELECT COUNT(ba.APK_ID) FROM BASE_APK ba WHERE 1=1 ";
	/**
	 * 查询app安装包版本数量
	 * @param apk
	 * @return
	 * @throws Exception
	 */
	public int selectApkNum(Apk apk) throws Exception{
		StringBuilder sql = new StringBuilder(selectApkNumSql);
		List<Object> params = new ArrayList<Object>();
		searchCondition(sql, params, apk);
		return this.queryForInt(sql.toString(), params);
	}

	/**
	 * 查询条件
	 * @param sql
	 * @param params
	 * @param apk
	 */
	private void searchCondition(StringBuilder sql, List<Object> params, Apk apk) {
		if(apk != null) {
			if(StringUtils.isNotEmpty(apk.getApkKey())){
				sql.append("AND ba.APK_KEY = ? ");
				params.add(apk.getApkKey());
			}
			if(StringUtils.isNotEmpty(apk.getApkVersion())){
				sql.append("AND ba.APK_VERSION = ? ");
				params.add(apk.getApkVersion());
			}
			if(StringUtils.isNotEmpty(apk.getApkId())){
				sql.append("AND ba.APK_ID = ? ");
				params.add(apk.getApkId());
			}
			if(apk.getApkForce() != null){
				sql.append("AND ba.APK_FORCE = ? ");
				params.add(apk.getApkForce());
			}
			if(apk.getApkState() != null){
				sql.append("AND ba.APK_STATE = ? ");
				params.add(apk.getApkState());
			}
		}
	}
}
